package com.yonyou.cms.epc.service.graphic.impl;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cms.epc.client.dto.graphic.GraphicModelDTO;
import com.yonyou.cms.epc.client.entity.CarModelPO;
import com.yonyou.cms.epc.client.entity.graphic.GraphicModelPO;
import com.yonyou.cms.epc.client.feign.BaseDataClient;
import com.yonyou.cms.epc.mapper.graphic.GraphicModelMapper;
import com.yonyou.cms.epc.service.graphic.GraphicModelService;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.UserDictDto;
import com.yonyou.cyxdms.sysmanage.client.service.login.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yzy
 * @since 2022-06-08
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GraphicModelServiceImpl extends ServiceImpl<GraphicModelMapper, GraphicModelPO> implements GraphicModelService {
    /** 日志对象 */
    private static final Logger logger = LoggerFactory.getLogger(GraphicModelServiceImpl.class);
    @Autowired
    GraphicModelMapper graphicModelMapper;

    @Autowired
    LoginService loginService;

    @Autowired
    public BaseDataClient baseDataClient;

    /**
     * 分页查询对应数据
     *
     * @param page 分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map<java.lang.String,java.lang.Object>>
     * @author yzy
     * @since 2018/7/22 0022
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        List<Map<String, Object>> modelList = graphicModelMapper.selectPageBySql(page, queryCondition);
        for(Map<String,Object> map : modelList) {
            UserDictDto createdUser = loginService.getUserById(Long.valueOf(map.get("createdBy").toString()));
            UserDictDto updatedUser = loginService.getUserById(Long.valueOf(map.get("updatedBy").toString()));
            if (updatedUser != null) {
                map.put("updatedByName", updatedUser.getUserName());
            }
            if (createdUser != null) {
                map.put("createdByName", createdUser.getUserName());
            }
        }
        // 获取总条数
        page.setRecords(modelList);
        return page;
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @author yzy
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String,Object >> selectListBySql(Map<String, Object> queryCondition) {
        return graphicModelMapper.selectListBySql(queryCondition);
    }



    /**
     * 根据查询条件返回结果集
     *
     * @param id 主键ID
     * @return java.util.List<java.util.Map < java.lang.String , java.lang.Object>>
     * @author yzy
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getById(Integer id) {
        GraphicModelPO graphicModelPo = graphicModelMapper.selectById(id);
        if(graphicModelPo!=null){
            return graphicModelPo.toMaps();
        }else{
            throw new DALException("查询失败,没有符合条件的数据");
        }
    }

    @Override
    public boolean insertBatch(List<GraphicModelPO> list) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        if(list!=null&&list.size()>0){
            List<Map<String, Object>> maps = graphicModelMapper.selectListBySql(new HashMap());
            for (int i=0;i<list.size();i++){
                for (Map<String, Object> map : maps) {
                    if(map.get("modelCode").equals(list.get(i).getModelCode())){
                        throw new DALException("车型代码"+list.get(i).getModelCode()+"重复");
                    }
                }
                list.get(i).setAppId(loginInfo.getAppId());
                list.get(i).setOwnerParCode(loginInfo.getOwnerParCode());
                list.get(i).setOwnerCode(loginInfo.getOwnerCode());
                list.get(i).setOrgId(loginInfo.getOrgId().toString());
                list.get(i).setCompanyCode(loginInfo.getCompanyCode());
                list.get(i).setCreatedBy(loginInfo.getUserId().toString());
                list.get(i).setUpdatedBy(loginInfo.getUserId().toString());
                list.get(i).setCreatedAt(LocalDateTime.now());
                list.get(i).setUpdatedAt(LocalDateTime.now());
                list.get(i).setAppId(loginInfo.getAppId());
            }
            if(graphicModelMapper.insertBatch(list)>0){
                return true;
            }
            throw new DALException("保存失败");
        }
        return true;
    }

    /**
     * 根据DTO 进行数据新增
     *
     * @param graphicModelDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String,Object> insert(GraphicModelDTO graphicModelDTO) {
        //对对象进行赋值操作
        GraphicModelPO graphicModelPo = graphicModelDTO.transDtoToPo(GraphicModelPO.class);
        //执行插入
        graphicModelMapper.insert(graphicModelPo);
        //返回插入的值
        return graphicModelMapper.selectById(graphicModelPo.getModelId()).toMaps();
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param id 主键ID
     * @param graphicModelDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String,Object> update(Integer id, GraphicModelDTO graphicModelDTO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        GraphicModelPO graphicModelPo = graphicModelMapper.selectById(id);
        graphicModelPo.setUpdatedBy(loginInfo.getUserId().toString());
        graphicModelPo.setUpdatedAt(LocalDateTime.now());
        //对对象进行赋值操作
        graphicModelDTO.transDtoToPo(graphicModelPo);
        //执行更新
        graphicModelMapper.updateById(graphicModelPo);
        return graphicModelPo.toMaps();
    }

    /**
     * 根据ID 进行删除数据
     *
     * @param id
     * @return void
     * @author zhangxianchao
     * @since 2018/8/25 0025
     */
    @Override
    public void deleteById(Integer id) {
        int deleteCount = graphicModelMapper.deleteById(id);
        logger.debug("删除数量：{}",deleteCount);
        if (deleteCount<=0) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    /**
     * 根据ids 进行批量删除
     *
     * @param ids
     * @return void
     * @author zhangxianchao
     * @since 2018/8/25 0025
     */
    @Override
    public void deleteBatchIds(String ids) {
        List<Integer> longList = StringUtils.convertStrToArray(ids,",", Integer.class);
        int deleteCount = graphicModelMapper.deleteBatchIds(longList);
        logger.debug("删除数量：{}",deleteCount);
        if (deleteCount!=longList.size()) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    @Override
    public Map<String, Object> imports(List<Map<String, Object>> datas) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<Map<String, Object>> errorData = new ArrayList<>();
        for(int i = 0; i < datas.size(); i++){
            Map<String, Object> row = datas.get(i);
            Map<String, Object> queryCondition=  new HashMap();
            Map<String, Object> modelCondition=  new HashMap();
            boolean isZhu=false;
            Integer modelId=0;
            //校验导入车型数据是否正确
            modelCondition.put("appId",loginInfo.getAppId());
            modelCondition.put("modelCode", row.get("modelCode").toString());
            //feign调用车型查询
            logger.debug("执行了获取车型系统列表:"+modelCondition.get("modelCode"));
            RestResultResponse<List<CarModelPO>> listRestResultResponse = baseDataClient.queryModelBySql(modelCondition);
            int rownum = i + 1;
            if(listRestResultResponse.getData().size()==0){
                errorData.add(new HashMap<String, Object>() {{
                    put("rownum", rownum);
                    put("errormsg", "车型代码不存在，导入失败！");
                }});
                continue;
            }

            //导入之前查询主表数据是否存在
            queryCondition.put("appId",loginInfo.getAppId());
            List<GraphicModelPO> parentList= graphicModelMapper.selectListPo(queryCondition);
            for (int j = 0; j < parentList.size(); j++) {
                if (parentList.get(j).getModelCode().equals(row.get("modelCode").toString())
                ) {
                    isZhu=true;
                    modelId = parentList.get(j).getModelId();
                }
            }


            if(isZhu){
                //修改
                LambdaUpdateWrapper<GraphicModelPO> updateWrapperZhu = new UpdateWrapper<GraphicModelPO>().lambda();
                updateWrapperZhu.eq(GraphicModelPO::getModelId, modelId);
                updateWrapperZhu.set(GraphicModelPO::getModelName,row.get("modelName").toString().trim());
                updateWrapperZhu.set(GraphicModelPO::getUpdatedAt,LocalDateTime.now());
                updateWrapperZhu.set(GraphicModelPO::getUpdatedBy,loginInfo.getUserId());
                graphicModelMapper.update(null, updateWrapperZhu);
            }else{
                //新增
                GraphicModelPO modelPo = new GraphicModelPO();
                modelPo.setModelCode(row.get("modelCode").toString());
                modelPo.setModelName(row.get("modelName").toString());
                graphicModelMapper.insert(modelPo);
            }
        }

        if (errorData.size() > 0) {
            return new HashMap<String, Object>() {{
                put("status", false);
                put("errorData", errorData);
            }};
        } else {
            return new HashMap<String, Object>() {{
                put("status", true);
            }};
        }
    }


}
